/* Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.flowable.app.rest.runtime;

import cmbchina.util.AjaxJson;
import cmbchina.util.FlowHttpRequestUtils;
import cmbchina.util.JacksonUitl;
import cmbchina.util.SystemCacheUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.apache.commons.lang3.StringUtils;
import org.flowable.app.cusTaskExe.CusTaskOptParams;
import org.flowable.app.domain.editor.Flow;
import org.flowable.app.domain.editor.FlowForm;
import org.flowable.app.model.runtime.CreateProcessInstanceRepresentation;
import org.flowable.app.model.runtime.ProcessInstanceRepresentation;
import org.flowable.app.rest.model.CusProcessInstanceRepresentation;
import org.flowable.app.service.editor.mapper.*;
import org.flowable.app.service.runtime.FlowableProcessInstanceQueryService;
import org.flowable.app.service.runtime.FlowableProcessInstanceService;
import org.flowable.bpmn.model.*;
import org.flowable.bpmn.model.Process;
import org.flowable.engine.*;
import org.flowable.engine.impl.RepositoryServiceImpl;
import org.flowable.engine.repository.Deployment;
import org.flowable.engine.repository.ProcessDefinition;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.engine.task.Event;
import org.flowable.form.api.FormRepositoryService;
import org.flowable.form.model.FormField;
import org.flowable.form.model.FormModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.sql.Timestamp;
import java.util.*;

@RestController
public class CusProcessInstancesResource {

    private static final Logger LOGGER = LoggerFactory.getLogger(CusProcessInstancesResource.class);
    @Autowired
    protected FlowableProcessInstanceService processInstanceService;

    @Autowired
    protected FormRepositoryService formRepositoryService;

    @Autowired
    protected HistoryService historyService;


    @Autowired
    protected TaskService taskService;

    @Autowired
    protected RuntimeService runtimeService;


    @Autowired
    protected FlowableProcessInstanceQueryService processInstanceQueryService;
    protected Map<String, InfoMapper> propertyMappers = new HashMap<>();

    public CusProcessInstancesResource() {
//        eventElementTypes.add("StartEvent");
//        eventElementTypes.add("EndEvent");
//        eventElementTypes.add("BoundaryEvent");
//        eventElementTypes.add("IntermediateCatchEvent");
//        eventElementTypes.add("ThrowEvent");

        propertyMappers.put("BoundaryEvent", new EventInfoMapper());
        propertyMappers.put("EndEvent", new EventInfoMapper());
        propertyMappers.put("IntermediateCatchEvent", new EventInfoMapper());
        propertyMappers.put("ReceiveTask", new ReceiveTaskInfoMapper());
        propertyMappers.put("StartEvent", new EventInfoMapper());
        propertyMappers.put("SequenceFlow", new SequenceFlowInfoMapper());
        propertyMappers.put("ServiceTask", new ServiceTaskInfoMapper());
        propertyMappers.put("ThrowEvent", new EventInfoMapper());
        propertyMappers.put("UserTask", new UserTaskInfoMapper());
    }

    @Autowired
    protected RepositoryServiceImpl repositoryService;

    /**
     * 接口启动流程（前提条件,开始节点必须配置好所有流程节点所需的参数）
     * @param startRequest 请求的参数
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/rest/cusProcessInstanceByKey", method = RequestMethod.POST)
    public AjaxJson cusProcessInstanceByKey(@RequestBody CusProcessInstanceRepresentation startRequest) throws Exception {

        //返回结果
        AjaxJson ajaxJson = new AjaxJson();

        Deployment deployment = repositoryService.createDeploymentQuery().deploymentKey(startRequest.getDeploymentKey()).latest().singleResult();

        //第一个节点是否是自定义页面
        boolean isCusForm = false;
        if (deployment != null) {
            //根据app的key和流程的key查询流程信息
            ProcessDefinition pd = repositoryService.createProcessDefinitionQuery().deploymentId(deployment.getId()).processDefinitionKey(startRequest.getProcessDefinitionKey()).singleResult();

            //判断流程是否 存在
            if(pd==null){
                ajaxJson.setSuccess(false);
                ajaxJson.setMsg("未找到对应的流程！");
                return ajaxJson;
            }
            startRequest.setProcessDefinitionId(pd.getId());
            BpmnModel pojoModel = repositoryService.getBpmnModel(pd.getId());
            Collection<FlowElement> flowElements1 = pojoModel.getMainProcess().getFlowElements();
            String formId = null;
            for(FlowElement e : flowElements1) {
                if(!(e instanceof SequenceFlow)) {
                    String type = e.getClass().getSimpleName();
                    if("StartEvent".equals(type)) {

                        StartEvent startEvent = (StartEvent) e;
                        if(startEvent.getFormKey()!=null){
                            if(startEvent.getFormKey().indexOf(".html")>=0){
                                isCusForm = true;
                                startRequest.setFormId("123456789");
                            }else{
                                FormModel formModel = formRepositoryService.getFormModelByKey(startEvent.getFormKey());
                                formId =formModel.getId();
                                startRequest.setFormId(formId);
                            }


                        };

                        break;
                    }
                }
            }

            if(isCusForm){
                return createProcessInstanceByCusForm(startRequest,pojoModel,isCusForm);
            }else{
                return createProcessInstance(startRequest,pojoModel,isCusForm);

            }

        }
        else{
            ajaxJson.setSuccess(false);
            ajaxJson.setMsg("deploymenKey错误！");
            return ajaxJson;
        }
    }

    @RequestMapping(value = "/rest/testPassword", method = RequestMethod.POST)
    public AjaxJson testPassword() throws Exception {

        AjaxJson ajaxJson = new AjaxJson();
//        startRequest.setProcessDefinitionId(pd.getId());
//        formRepositoryService.getform
        String password = this.getPassword("123","456");
        ajaxJson.setMsg(password);
        return ajaxJson;
    }

    /**
     * db2白名单授权生成密码
     * @param hostname
     * @param grantee
     * @return
     */
    public String getPassword(String hostname,String grantee){
        try {
            String classPath = this.getClass().getResource("").getPath();
            String shpath= "ksh " + classPath  +"password.sh "+grantee+ " " + hostname;
            System.out.println("db2 whiteList shpath:" + shpath);
            java.lang.Process ps = Runtime.getRuntime().exec(shpath);
            ps.waitFor();


            BufferedReader br = new BufferedReader(new InputStreamReader(ps.getInputStream()));
            StringBuffer sb = new StringBuffer();
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            String result = sb.toString();
            System.out.println("db2 whiteList password:" + result);
            return result;
        }
        catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }


    /**
     * 开启一个流程实例
     * @param startRequest
     * @param pojoModel
     * @param isCusForm
     * @return
     */
    public AjaxJson createProcessInstance(CusProcessInstanceRepresentation startRequest,BpmnModel pojoModel,boolean isCusForm){
        AjaxJson returnAjaxJson = new AjaxJson();
        try{



            ProcessInstanceRepresentation pir = processInstanceService.startNewProcessInstance(startRequest);
            LOGGER.info("开始了一个任务======"+pir.getId());

            Collection<FlowElement> flowElements = pojoModel.getMainProcess().getFlowElements();
            Flow cusFlow = new Flow();
            cusFlow.setProcessInstId(pir.getId());
            cusFlow.setState(1);

            cusFlow.setCreateUserId(startRequest.getUserId());
            cusFlow.setCreateUserName(startRequest.getUserName());
            cusFlow.setDeploymentKey(startRequest.getDeploymentKey());
            cusFlow.setCreateTime(new Timestamp(System.currentTimeMillis()));
            if(StringUtils.isNotBlank(startRequest.getFormId())){
                cusFlow.setStartTime(new Timestamp(System.currentTimeMillis()));
            }
            cusFlow.setStartForm(startRequest.getFormId());
            cusFlow.setFlowTemp(pir.getProcessDefinitionName());
            cusFlow.setFlowTempId(pir.getProcessDefinitionId());
            cusFlow.setName(startRequest.getName());
            ObjectMapper mapper = new ObjectMapper();
            String cusFlowParmas = mapper.writeValueAsString(cusFlow);
            LOGGER.info("/api/flows" + cusFlowParmas);
            FlowHttpRequestUtils.httpRequestPost("/api/flows", cusFlowParmas);
            List<Process> pro = pojoModel.getProcesses();

            String startElementFormKey = "";
            String taskDefinitionKey = "";
            int index = 0 ;
            for(FlowElement e : flowElements) {
                if(!(e instanceof SequenceFlow)){
                    FlowForm cusFlowForm = new FlowForm();

                    String type = e.getClass().getSimpleName();
                    cusFlowForm.setTaskType(type);
                    if(type.equals("UserTask")){
//                    type = "UserTask-CUS";

                        UserTask es = (UserTask) e;
                        List<FlowableListener>  taskListener =es.getTaskListeners();

                        for(FlowableListener fl:taskListener)
                        {
                            String cusTaskTyep = fl.getImplementation();
                            boolean test = SystemCacheUtil.getInst().getCusTaskMap().containsKey(cusTaskTyep);
                            cusFlowForm.setTaskType(SystemCacheUtil.getInst().getCusTaskMap().get(fl.getImplementation()));
                            continue;
//                        String value = fl.get;
                        }

                    }
                    if (propertyMappers.containsKey(type)) {

                        ArrayNode proNode = propertyMappers.get(type).map(e);
                        for(JsonNode obj:proNode){

                            String key = obj.get("name").asText();
                            if("Form key".equals(key)){

                                String value = obj.get("value").asText();
                                if(value.indexOf(".html")<0){

                                    cusFlowForm.setFromInfo(this.optFormInfo(value,pir.getId(),e.getId(),null));
                                }

                                cusFlowForm.setFormKey(value);
                            }
                        }
                    }
                    if(StringUtils.isNotBlank(startElementFormKey)&&index==0){
                        taskDefinitionKey = e.getId();
                        index = 1;
                    }
                    cusFlowForm.setResultState("1");//参数为空、准备中
                    //如果开始节点绑定过了表单信息
                    if(startRequest.getFormId()!=null){
                        if("StartEvent".equals(type)){

                            StartEvent startEvent = (StartEvent) e;
                            startElementFormKey = startEvent.getFormKey();
                            cusFlowForm.setFormKey(startElementFormKey);

                            cusFlowForm.setResultState("5");//参数为空、准备中
                            Map formInfoMap = new LinkedHashMap<>();
                            Map formMap = new LinkedHashMap<>();
                            formInfoMap.put("formId",startRequest.getFormId());
                            formInfoMap.put("values",startRequest.getValues());
                            formMap.put("formInfo",formInfoMap);
                            formMap.put("taskDefinitionKey",e.getId());
                            formMap.put("processInstId",pir.getId());
                            formMap.put("outcome",null);
                            cusFlowForm.setFromInfo(JacksonUitl.getObjectMapper().writeValueAsString(formMap));
                        }
                    }

                    cusFlowForm.setProcessInstId(pir.getId());
//            cusFlowForm.setCreateTime(System.currentTimeMillis());
                    cusFlowForm.setTaskDefinitionKey(e.getId());
                    cusFlowForm.setTaskName(e.getName());
                    String mapJakcson = mapper.writeValueAsString(cusFlowForm);
                    FlowHttpRequestUtils.httpRequestPost("/api/flow-forms",mapJakcson );
                    LOGGER.error("/api/flow-forms" + mapJakcson);
                }



            }
            String password = "";
            LOGGER.info("判断是否是db2的白名单提权流程，如果是做返回用户名和密码的功能特殊处理，相关信息："+ startRequest.getProcessDefinitionKey());
            if("db2WhiteListFlow".equals(startRequest.getProcessDefinitionKey())){
                LOGGER.info("进入了判断是否是db2的白名单提权流程逻辑，ProcessDefinitionKey："+ startRequest.getProcessDefinitionKey());
                Map<String,Object> paramsMap = startRequest.getValues();
                password = this.getPassword(paramsMap.get("hostname").toString(),paramsMap.get("grantee").toString());
                SystemCacheUtil.whiteListPasswordMap.put(pir.getId(),password);
                LOGGER.info("进入了判断是否是db2的白名单提权流程逻辑，ProcessDefinitionKey："+ startRequest.getProcessDefinitionKey()+"密码："+password);
                LOGGER.info("存放密码的map："+ SystemCacheUtil.whiteListPasswordMap);

            }
            if(StringUtils.isNotBlank(startElementFormKey)){


                AjaxJson ajaxJson = new CusTaskOptParams().optRunTaskparams(historyService,taskService,pir.getId());
                returnAjaxJson.setMsg(ajaxJson.getMsg());
                returnAjaxJson.setSuccess(ajaxJson.isSuccess());
            }

            if(returnAjaxJson.isSuccess()){
                if("db2WhiteListFlow".equals(startRequest.getProcessDefinitionKey())){

                    Map<String,Object> paramsMap = startRequest.getValues();
                    pir.setName(paramsMap.get("grantee").toString());
                    pir.setBusinessKey(password);
                }
            }
            returnAjaxJson.setObj(pir);
        }catch (Exception e){
            LOGGER.error(e.getMessage(),e);
            returnAjaxJson.setSuccess(false);
            returnAjaxJson.setMsg(e.getMessage());
        }



        return returnAjaxJson;
    }


    /**
     * 接口开启+第一个节点是自定义页面的流程
     * @param startRequest
     * @param pojoModel
     * @param isCusForm
     * @return
     */
    public AjaxJson createProcessInstanceByCusForm(CusProcessInstanceRepresentation startRequest,BpmnModel pojoModel,boolean isCusForm){
        AjaxJson returnAjaxJson = new AjaxJson();
        try{



            ProcessInstance pir = runtimeService.startProcessInstanceById(startRequest.getProcessDefinitionId(),startRequest.getValues(),startRequest.getName());
            LOGGER.error("开始了一个任务======"+pir.getId());

            Collection<FlowElement> flowElements = pojoModel.getMainProcess().getFlowElements();
            Flow cusFlow = new Flow();
            cusFlow.setProcessInstId(pir.getId());
            cusFlow.setState(1);

            cusFlow.setCreateUserId(startRequest.getUserId());
            cusFlow.setCreateUserName(startRequest.getUserName());
            cusFlow.setDeploymentKey(startRequest.getDeploymentKey());
            cusFlow.setCreateTime(new Timestamp(System.currentTimeMillis()));
            if(StringUtils.isNotBlank(startRequest.getFormId())){
                cusFlow.setStartTime(new Timestamp(System.currentTimeMillis()));
            }
            cusFlow.setStartForm(startRequest.getFormId());
            cusFlow.setFlowTemp(pir.getProcessDefinitionName());
            cusFlow.setFlowTempId(pir.getProcessDefinitionId());
            cusFlow.setName(startRequest.getName());
            ObjectMapper mapper = new ObjectMapper();
            String cusFlowParmas = mapper.writeValueAsString(cusFlow);
            LOGGER.error("/api/flows" + cusFlowParmas);
            FlowHttpRequestUtils.httpRequestPost("/api/flows", cusFlowParmas);
            List<Process> pro = pojoModel.getProcesses();

            String startElementFormKey = "";
            String taskDefinitionKey = "";
            int index = 0 ;
            for(FlowElement e : flowElements) {
                if(!(e instanceof SequenceFlow)){
                    FlowForm cusFlowForm = new FlowForm();

                    String type = e.getClass().getSimpleName();
                    cusFlowForm.setTaskType(type);
                    if(type.equals("UserTask")){
//                    type = "UserTask-CUS";

                        UserTask es = (UserTask) e;
                        List<FlowableListener>  taskListener =es.getTaskListeners();

                        for(FlowableListener fl:taskListener)
                        {
                            String cusTaskTyep = fl.getImplementation();
                            boolean test = SystemCacheUtil.getInst().getCusTaskMap().containsKey(cusTaskTyep);
                            cusFlowForm.setTaskType(SystemCacheUtil.getInst().getCusTaskMap().get(fl.getImplementation()));
                            continue;
//                        String value = fl.get;
                        }

                    }
                    if (propertyMappers.containsKey(type)) {

                        ArrayNode proNode = propertyMappers.get(type).map(e);
                        for(JsonNode obj:proNode){

                            String key = obj.get("name").asText();
                            if("Form key".equals(key)){

                                String value = obj.get("value").asText();
                                if(value.indexOf(".html")<0){

                                    cusFlowForm.setFromInfo(this.optFormInfo(value,pir.getId(),e.getId(),null));
                                }

                                cusFlowForm.setFormKey(value);
                            }
                        }
                    }
                    if(StringUtils.isNotBlank(startElementFormKey)&&index==0){
                        taskDefinitionKey = e.getId();
                        index = 1;
                    }
                    cusFlowForm.setResultState("1");//参数为空、准备中
                    //如果开始节点绑定过了表单信息
                    if(startRequest.getFormId()!=null){
                        if("StartEvent".equals(type)){

                            StartEvent startEvent = (StartEvent) e;
                            startElementFormKey = startEvent.getFormKey();
                            cusFlowForm.setFormKey(startElementFormKey);

                            cusFlowForm.setResultState("5");//参数为空、准备中
                            Map formInfoMap = new LinkedHashMap<>();
                            Map formMap = new LinkedHashMap<>();
                            formInfoMap.put("formId",startRequest.getFormId());
                            formInfoMap.put("values",startRequest.getValues());
                            formMap.put("formInfo",formInfoMap);
                            formMap.put("taskDefinitionKey",e.getId());
                            formMap.put("processInstId",pir.getId());
                            formMap.put("outcome",null);
                            cusFlowForm.setFromInfo(JacksonUitl.getObjectMapper().writeValueAsString(formMap));
                        }
                    }

                    cusFlowForm.setProcessInstId(pir.getId());
//            cusFlowForm.setCreateTime(System.currentTimeMillis());
                    cusFlowForm.setTaskDefinitionKey(e.getId());
                    cusFlowForm.setTaskName(e.getName());
                    String mapJakcson = mapper.writeValueAsString(cusFlowForm);
                    FlowHttpRequestUtils.httpRequestPost("/api/flow-forms",mapJakcson );
                    LOGGER.error("/api/flow-forms" + mapJakcson);
                }



            }
            String password = "";
            LOGGER.error("判断是否是db2的白名单提权流程，如果是做返回用户名和密码的功能特殊处理，相关信息："+ startRequest.getProcessDefinitionKey());
            if("db2WhiteListFlow".equals(startRequest.getProcessDefinitionKey())){
                LOGGER.info("进入了判断是否是db2的白名单提权流程逻辑，ProcessDefinitionKey："+ startRequest.getProcessDefinitionKey());
                Map<String,Object> paramsMap = startRequest.getValues();
                password = this.getPassword(paramsMap.get("hostname").toString(),paramsMap.get("grantee").toString());
                SystemCacheUtil.whiteListPasswordMap.put(pir.getProcessInstanceId(),password);
                LOGGER.info("进入了判断是否是db2的白名单提权流程逻辑，ProcessDefinitionKey："+ startRequest.getProcessDefinitionKey()+"密码："+password);
                LOGGER.info("存放密码的map："+ SystemCacheUtil.whiteListPasswordMap);

            }
            if(StringUtils.isNotBlank(startElementFormKey)){


                AjaxJson ajaxJson = new CusTaskOptParams().optRunTaskparams(historyService,taskService,pir.getId());
                returnAjaxJson.setMsg(ajaxJson.getMsg());
                returnAjaxJson.setSuccess(ajaxJson.isSuccess());
            }

            ProcessInstanceRepresentation pp = new ProcessInstanceRepresentation();
            if(returnAjaxJson.isSuccess()){
                if("db2WhiteListFlow".equals(startRequest.getProcessDefinitionKey())){

                    pp.setName(startRequest.getValues().get("grantee").toString());
                    pp.setBusinessKey(password);
                    pp.setId(pir.getId());
                }
            }
            returnAjaxJson.setObj(pp);
        }catch (Exception e){
            LOGGER.error(e.getMessage(),e);
            returnAjaxJson.setSuccess(false);
            returnAjaxJson.setMsg(e.getMessage());
        }



        return returnAjaxJson;
    }
    @RequestMapping(value = "/rest/cus-process-instances", method = RequestMethod.POST)
    public AjaxJson startNewProcessInstance(@RequestBody CusProcessInstanceRepresentation startRequest) throws Exception {
        BpmnModel pojoModel = repositoryService.getBpmnModel(startRequest.getProcessDefinitionId());
        return createProcessInstance(startRequest,pojoModel,false);
    }


    /**
     * 第一个节点是自定义页面而且是通过前端调用发起一个流程实例
     * @param startRequest
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/rest/startNewProcessInstanceByCusForm", method = RequestMethod.POST)
    public AjaxJson startNewProcessInstanceByCusForm(@RequestBody CusProcessInstanceRepresentation startRequest) throws Exception {

        AjaxJson returnAjaxJson = new AjaxJson();
        try{
            ProcessInstance pir = runtimeService.startProcessInstanceById(startRequest.getProcessDefinitionId(),startRequest.getValues(),startRequest.getName());
            BpmnModel pojoModel = repositoryService.getBpmnModel(pir.getProcessDefinitionId());
            Collection<FlowElement> flowElements = pojoModel.getMainProcess().getFlowElements();
            Flow cusFlow = new Flow();
            cusFlow.setProcessInstId(pir.getId());
            cusFlow.setState(1);
            cusFlow.setCreateUserId(startRequest.getUserId());
            cusFlow.setCreateUserName(startRequest.getUserName());
            cusFlow.setDeploymentKey(startRequest.getDeploymentKey());
            cusFlow.setCreateTime(new Timestamp(System.currentTimeMillis()));
            if(StringUtils.isNotBlank(startRequest.getFormId())){
                cusFlow.setStartTime(new Timestamp(System.currentTimeMillis()));
            }
            cusFlow.setStartForm(startRequest.getFormId());
            cusFlow.setFlowTemp(pir.getProcessDefinitionName());
            cusFlow.setFlowTempId(pir.getProcessDefinitionId());
            cusFlow.setName(startRequest.getName());
            ObjectMapper mapper = new ObjectMapper();
            String cusFlowParmas = mapper.writeValueAsString(cusFlow);
            LOGGER.error("/api/flows" + cusFlowParmas);
            FlowHttpRequestUtils.httpRequestPost("/api/flows", cusFlowParmas);
            List<Process> pro = pojoModel.getProcesses();

            String startElementFormKey = "";
            String taskDefinitionKey = "";
            int index = 0 ;
            for(FlowElement e : flowElements) {
                if(!(e instanceof SequenceFlow)){
                    FlowForm cusFlowForm = new FlowForm();

                    String type = e.getClass().getSimpleName();
                    cusFlowForm.setTaskType(type);
                    if(type.equals("UserTask")){
//                    type = "UserTask-CUS";

                        UserTask es = (UserTask) e;
                        List<FlowableListener>  taskListener =es.getTaskListeners();

                        for(FlowableListener fl:taskListener)
                        {
                            String cusTaskTyep = fl.getImplementation();
                            boolean test = SystemCacheUtil.getInst().getCusTaskMap().containsKey(cusTaskTyep);
                            cusFlowForm.setTaskType(SystemCacheUtil.getInst().getCusTaskMap().get(fl.getImplementation()));
                            continue;
//                        String value = fl.get;
                        }

                    }
                    if (propertyMappers.containsKey(type)) {

                        ArrayNode proNode = propertyMappers.get(type).map(e);
                        for(JsonNode obj:proNode){

                            String key = obj.get("name").asText();
                            if("Form key".equals(key)){

                                String value = obj.get("value").asText();
                                if(value.indexOf(".html")<0){

                                    cusFlowForm.setFromInfo(this.optFormInfo(value,pir.getId(),e.getId(),null));
                                }

                                cusFlowForm.setFormKey(value);
                            }
                        }
                    }
                    if(StringUtils.isNotBlank(startElementFormKey)&&index==0){
                        taskDefinitionKey = e.getId();
                        index = 1;
                    }
                    cusFlowForm.setResultState("1");//参数为空、准备中
                    //如果开始节点绑定过了表单信息
                    if(startRequest.getFormId()!=null){
                        if("StartEvent".equals(type)){

                            StartEvent startEvent = (StartEvent) e;
                            startElementFormKey = startEvent.getFormKey();
                            cusFlowForm.setFormKey(startElementFormKey);

                            cusFlowForm.setResultState("5");//参数为空、准备中
                            Map formInfoMap = new LinkedHashMap<>();
                            Map formMap = new LinkedHashMap<>();
                            formInfoMap.put("formId",startRequest.getFormId());
                            formInfoMap.put("values",startRequest.getValues());
                            formMap.put("formInfo",formInfoMap);
                            formMap.put("taskDefinitionKey",e.getId());
                            formMap.put("processInstId",pir.getId());
                            formMap.put("outcome",null);
                            cusFlowForm.setFromInfo(JacksonUitl.getObjectMapper().writeValueAsString(formMap));
                        }
                    }

                    cusFlowForm.setProcessInstId(pir.getId());
//            cusFlowForm.setCreateTime(System.currentTimeMillis());
                    cusFlowForm.setTaskDefinitionKey(e.getId());
                    cusFlowForm.setTaskName(e.getName());
                    String mapJakcson = mapper.writeValueAsString(cusFlowForm);
                    FlowHttpRequestUtils.httpRequestPost("/api/flow-forms",mapJakcson );
                    LOGGER.error("/api/flow-forms" + mapJakcson);
                }



            }
            String password = "";
            LOGGER.info("判断是否是db2的白名单提权流程，如果是做返回用户名和密码的功能特殊处理，相关信息："+ startRequest.getProcessDefinitionKey());
            if(startRequest.getProcessDefinitionId().indexOf("db2WhiteListFlow")>=0){
                LOGGER.info("进入了判断是否是db2的白名单提权流程逻辑，ProcessDefinitionKey："+ startRequest.getProcessDefinitionKey());
                Map<String,Object> paramsMap = startRequest.getValues();
                password = this.getPassword(paramsMap.get("hostname").toString(),paramsMap.get("grantee").toString());
                SystemCacheUtil.whiteListPasswordMap.put(pir.getProcessInstanceId(),password);
                LOGGER.info("进入了判断是否是db2的白名单提权流程逻辑，ProcessDefinitionKey："+ startRequest.getProcessDefinitionKey()+"密码："+password);
                LOGGER.info("存放密码的map："+ SystemCacheUtil.whiteListPasswordMap);

            }
            if(StringUtils.isNotBlank(startElementFormKey)){

                AjaxJson ajaxJson = new CusTaskOptParams().optRunTaskparams(historyService,taskService,pir.getId());
            }
            ProcessInstanceRepresentation pirReturn = new ProcessInstanceRepresentation();
            pirReturn.setId(pir.getId());
            returnAjaxJson.setObj(pirReturn);

        }catch (Exception e){
            LOGGER.error(e.getMessage(),e);
            returnAjaxJson.setSuccess(false);
            returnAjaxJson.setMsg(e.getMessage());
        }


        return returnAjaxJson;
    }

    @RequestMapping(value = "/rest/isEnd/{processInstId}", method = RequestMethod.POST)
    public AjaxJson isEnd(@PathVariable String processInstId) throws Exception {
//        startRequest.setName("zm-测试任务名称");

        AjaxJson ajaxJson = new AjaxJson();
//        return pir;
        return ajaxJson;
    }

    /**
     * 查询并处理表单
     * @param formKey
     */
    public Map<String,String> optFormModel(String formKey){

        FormModel formModel =this.formRepositoryService.getFormModelByKey(formKey);
        Map<String,String> formModelMap = new LinkedHashMap<>();
        for(FormField field:formModel.getFields()){

            formModelMap.put(field.getId(),field.getValue()!=null?field.getValue().toString():null);
        }
        return formModelMap;
    }

    /**
     * 查询并处理表单
     * @param formKey
     */
    public String optFormInfo(String formKey,String processInstId,String taskDefinitionKey,String outcome)  {

        FormModel formModel =this.formRepositoryService.getFormModelByKey(formKey);
        Map<String,Object> formInfoMap = new LinkedHashMap<>();
        Map<String,Object> taskFormMap = new LinkedHashMap<>();
        taskFormMap.put("formId",formModel.getId());
        taskFormMap.put("values",this.optFormModel(formKey));
        formInfoMap.put("processInstId",processInstId);
        formInfoMap.put("taskDefinitionKey",taskDefinitionKey);
        formInfoMap.put("outcome",outcome);
        formInfoMap.put("formInfo",taskFormMap);
        try {
            return JacksonUitl.getObjectMapper().writeValueAsString(formInfoMap);
        } catch (JsonProcessingException e) {
            LOGGER.error("",e);
            return "";
        }
    }


}
